package cn.com.lyb.mrs.service;

import cn.com.lyb.mrs.config.SSLUtil;
import cn.com.lyb.mrs.controller.TestController;
import cn.com.lyb.mrs.dto.requestDTO.JobActionResquest;
import cn.com.lyb.mrs.dto.requestDTO.JobRequest;
import cn.com.lyb.mrs.dto.requestDTO.TenantRequest;
import cn.com.lyb.mrs.dto.responseDTO.TenantResponse;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;

@Component
public class ExecService {

    private static final Logger logger = LoggerFactory.getLogger(ExecService.class);

    @Autowired
    private RestTemplate restTemplate;

    private static final String CONTENT_TYPE = "application/x-www-form-urlencoded; charset=utf-8";
    private static final String X_REQUESTED_WITH = "XMLHttpRequest";


    @Value("${base-mrs-url}")//  https://ip:port
    private String baseMrsUrl;


    public void saveTenant(TenantRequest tenantRequest) throws NoSuchAlgorithmException, KeyManagementException {
        SSLUtil.turnOffSslChecking();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("X-Requested-With", "XMLHttpRequest");

        JSONObject data = new JSONObject();
        data.put("tenantId", tenantRequest.getTenantId());
        data.put("tenantName", tenantRequest.getTenantName());
        data.put("createUser", tenantRequest.getCreateUser());
        data.put("remark",tenantRequest.getRemark());
        HttpEntity<String> httpEntity = new HttpEntity<>(data.toString(), headers);
        String url = baseMrsUrl + "/flink/v1/tenants";
        JSONObject jsonObject = doPostForObject(url, httpEntity);
        JSONObject resultJSON = (JSONObject) jsonObject.get("result");
        TenantResponse tenantResponse = JSON.parseObject(String.valueOf(resultJSON), TenantResponse.class);
    }

    public void uploadJar(String tenantId, File file) throws NoSuchAlgorithmException, KeyManagementException {
        SSLUtil.turnOffSslChecking();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        headers.add("X-Requested-With", X_REQUESTED_WITH);
        headers.add("Language", "zh_CN");
        MultiValueMap<String, Object> formData = new LinkedMultiValueMap<>();
        formData.add("tenantId", tenantId);

        try (InputStream fileInputStream = new FileInputStream(file)) {
            formData.add("file", new InputStreamResource(fileInputStream) {
                @Override
                public String getFilename() {
                    return file.getName();
                }
            });
        } catch (Exception e) {
            logger.error("读取文件出错: " + e.getMessage());
            throw new RuntimeException(e);
        }
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(formData, headers);
        String url = baseMrsUrl = "/flink/file/job/uploadjar";
        doPostForObject(url, requestEntity);
    }

    public void saveWork(JobRequest jobRequest) throws NoSuchAlgorithmException, KeyManagementException {
        SSLUtil.turnOffSslChecking();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("X-Requested-With", "XMLHttpRequest");
        JSONObject data = new JSONObject();
        data.put("tenantId", jobRequest.getTenantId());
        data.put("jobId", jobRequest.getJobId());
        data.put("jobName", jobRequest.getJobName());
        data.put("jobType",jobRequest.getJobType());
        data.put("jobKind",jobRequest.getJobKind());
        data.put("remark",jobRequest.getRemark());
        HttpEntity<String> httpEntity = new HttpEntity<>(data.toString(), headers);
        String url = baseMrsUrl + "/flink/v1/" + jobRequest.getTenantId() + "/jobs";
        JSONObject jsonObject = doPostForObject(url, httpEntity);
    }

    public void actionWork(JobActionResquest actionResquest) throws NoSuchAlgorithmException, KeyManagementException {
        SSLUtil.turnOffSslChecking();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("X-Requested-With", "XMLHttpRequest");
        JSONObject data = new JSONObject();
        data.put("jobId", actionResquest.getJobId());
        data.put("action", actionResquest.getAction());
        data.put("isHms",actionResquest.getHms());
        HttpEntity<String> httpEntity = new HttpEntity<>(data.toString(), headers);
        String url = baseMrsUrl + "flink/v1/" + actionResquest.getTenantId()+ "/jobs/action";
        doPostForObject(url, httpEntity);
    }


    public JSONObject doPostForObject(String url, HttpEntity httpEntity) {
        logger.info("调用url:{}", url);
        try {
            ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);
            String result = exchange.getBody();
            logger.info("post类型接口调用返回信息:{}", result);
            return getJsonObject(result);
        } catch (RuntimeException be) {
            throw be;
        } catch (Exception e) {
            logger.error("post类型接口调用失败:{}", e);
            throw new RuntimeException(e.getMessage());
        }
    }

    public JSONObject doGetForObject(String url, HttpEntity httpEntity) {
        logger.info("调用url:{}", url);
        try {
            ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class);
            String result = exchange.getBody();
            logger.info("get类型接口调用返回信息:{}", result);
            return getJsonObject(result);
        } catch (RuntimeException be) {
            throw be;
        } catch (Exception e) {
            logger.error("get类型接口调用失败:{}", e);
            throw new RuntimeException(e.getMessage());
        }
    }

    public JSONObject doPutForObject(String url, HttpEntity httpEntity) {
        logger.info("调用url:{}", url);
        try {
            ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.PUT, httpEntity, String.class);
            String result = exchange.getBody();
            logger.info("put类型接口调用返回信息:{}", result);
            return getJsonObject(result);
        } catch (RuntimeException be) {
            throw be;
        } catch (Exception e) {
            logger.error("put类型接口调用失败:{}", e);
            throw new RuntimeException(e.getMessage());
        }
    }


    public JSONObject doDeleteForObject(String url, HttpEntity httpEntity) {
        logger.info("调用url:{}", url);
        try {
            ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.DELETE, httpEntity, String.class);
            String result = exchange.getBody();
            logger.info("delete类型接口调用返回信息:{}", result);
            return getJsonObject(result);
        } catch (RuntimeException be) {
            throw be;
        } catch (Exception e) {
            logger.error("delete类型接口调用失败:{}", e);
            throw new RuntimeException(e.getMessage());
        }
    }

    private static JSONObject getJsonObject(String result) {
        JSONObject resultJSON = JSON.parseObject(result);
        Integer resultCode = (Integer) resultJSON.get("resultCode");
        if (0 != resultCode.intValue()) {
            logger.error("调用结果返回异常:{}", result);
            throw new RuntimeException(resultJSON.get("MSG").toString());
        }
        return resultJSON;
    }



}
